package leetcode_动态规划._02矩阵路径;

/**
 * 最小路径和
 * 算法：
 *   动态规划
 *   由于只能向下或者向右，所以第一行和第一列的距离都已经知道了
 *   dp[i] = Math.min(dp[i - 1], dp[i])
 */
public class _64 {

    public int minPathSum(int[][] grid) {
        int[] dp = new int[grid[0].length + 1];
        for (int i = 0; i < grid.length; i++) {
            dp[1] = dp[1] + grid[i][0];
            for (int j = 1; j < grid[i].length; j++) {
                if (i == 0) {
                    dp[j + 1] = dp[j] + grid[i][j];
                    continue;
                }
                dp[j + 1] = Math.min(dp[j], dp[j + 1]) + grid[i][j];
            }
        }
        return dp[grid[0].length];
    }
}
